package com.xzq.bugstack.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.EmptyByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 11:19
 * @Version 1.0.0
 **/
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            DefaultHttpRequest request = (DefaultHttpRequest) msg;
            System.out.println("URI: " + request.getUri());
//            System.out.println(msg);
        }

        if (msg instanceof HttpContent) {
            LastHttpContent httpBody = (LastHttpContent) msg;
            ByteBuf byteBuf = httpBody.content();
            if (!(byteBuf instanceof EmptyByteBuf)) {
                //接受消息
                byte[] msgbytes = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(msgbytes);
                System.out.println(new String(msgbytes, Charset.forName("utf-8")));
            }
        }

        String responseMsg = "<hr>I am Http Server </hr>";
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_0,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(responseMsg.getBytes(Charset.forName("utf-8"))));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
        ctx.flush();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}
